package com.xiaojie.service;

import com.xiaojie.loabalance.LoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RefreshScope
public class OrderService {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancer loadBalancer;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Value("${xiaojie.name}")
    private String name;
    @GetMapping("/orderTomember")
    public  Object orderTomember(){
        //1、根据服务名称从注册中心获取服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("xiaojie-member");
        //2、列表任意选择一个，实现本地调用
        ServiceInstance singleAddress = loadBalancer.getSingleAddress(instances);
        //ServiceInstance serviceInstance = instances.get(0);
        String result = restTemplate.getForObject(singleAddress.getUri()+"/getMember", String.class);
        return result ;
    }

        @GetMapping("/getNacos")
        public String getNacos(){
            return "从配置文件读取到的内容"+name;
        }
    @GetMapping("/orderRibonTomember")
    public  Object orderRibonTomember(){
        String result = restTemplate.getForObject("http://xiaojie-member"+"/getMember", String.class);
        return result ;
    }
    @GetMapping("/orderBalanceClient")
    public Object orderBalanceClient(){
        ServiceInstance result = loadBalancerClient.choose("xiaojie-member");
        return result;
    }
}
